import { FormOutlined, MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { Button, Input, InputNumber, Tooltip } from 'antd';
import { nanoid } from 'nanoid';
import { useEffect, useState } from 'react';
import { connect } from 'umi';
import './index.less';

const GeneralCon: React.FC<any> = (props: any) => {
  const { keyPoints, loading, structWrite, setAgoLogs } = props;
  const { TextArea } = Input;
  const [disabled, setDisabled] = useState<boolean>(true);
  const [points, setPoints] = useState<any>([]);
  const [edit, setEdit] = useState(false);
  const [labelStyle, setLabelStyle] = useState({}); //label的宽度 根据标题长度计算 一个字符15px
  const [articlesNumTip, setArticlesNumTip] = useState(
    '小麦支持同时生成多篇文章，建议您多选择几篇进行生成',
  );
  const { articles_expected } = props.highClassWrite;
  const [articlesNum, setArticlesNum] = useState(0);
  //公共更新model的方法
  // const updateState = (updateObj: any) => {
  //   props.dispatch({
  //     type: 'highClassWrite/updateState',
  //     payload: updateObj,
  //   });
  // };
  //动态计算labelWidth的宽度
  const computeLabelWidth = () => {
    let lWidth = 0;
    points.forEach(async (item: any) => {
      const titleLength = item.title.length || 1;
      const addWidth = item.can_add === 1 && edit ? 30 : 0; //添加图标的宽度
      if (titleLength * 18 > lWidth) {
        lWidth = titleLength * 18 + addWidth;
      }
    });
    setLabelStyle({
      width: `${lWidth}px`,
    });
  };
  //初始化
  useEffect(() => {
    if (props?.highClassWrite?.docCommonInfo.key_points) {
      let anchorObj = props?.highClassWrite?.docCommonInfo.key_points.find(
        (item: any) => item.is_list === 1,
      );
      const titleWithoutNumber = anchorObj?.title?.replace(/\d+/g, '');
      const keyPointsNew = props?.highClassWrite?.docCommonInfo.key_points.map((item: any) => {
        if (anchorObj && item.title === anchorObj.title) {
          item.anchor = true;
          item.anchorName = titleWithoutNumber;
        } else if (anchorObj) {
          item.anchor = false;
          item.anchorName = titleWithoutNumber;
        }
        return {
          key: nanoid(),
          ...item,
        };
      });
      setPoints(keyPointsNew);
      computeLabelWidth();
    }
  }, [props?.highClassWrite?.docCommonInfo.key_points]);

  //要点列表变动时 触发计算label宽度
  useEffect(() => {
    if (points) {
      computeLabelWidth();
    }
  }, [points]);
  //编辑状态
  const editAglin = (edit: boolean) => {
    setEdit(edit);
    setDisabled(!edit);
    computeLabelWidth();
  };
  //点击生成
  const general = () => {
    points.forEach((element: any) => {
      console.log();
      if (element.anchorName) {
        delete element.anchorName;
        delete element.anchor;
      }
    });
    setEdit(false);
    setDisabled(true);
    //更新setAgoLogs  type='system'里的key_points = points
    setAgoLogs((prevLogs: any) => {
      return prevLogs.map((log: any) => {
        if (log.type === 'system') {
          return { ...log, key_points: points }; // 更新 key_points
        }
        return log; // 其他类型的日志保持不变
      });
    });
    structWrite(null, points, articlesNum);
  };

  const handleChangeParaEdit = (index: number, e: any) => {
    const newPoints = [...points];
    newPoints[index].content = e.target.value || '';
    setPoints(newPoints);
  };
  //添加一行
  const addItem = (index: number) => {
    const pointsCopy: any = [...points];
    const item = pointsCopy[index];
    const item_new = {
      key: nanoid(),
      title: item.title,
      content: '',
      can_add: item.can_add,
    };
    pointsCopy.splice(index + 1, 0, item_new);
    setPoints(pointsCopy);
  };
  //添加一行
  const addItem2 = (index: number) => {
    const pointsCopy: any = [...points];
    const item = pointsCopy[index];
    // 构建新的项，序列号设置为数量加 1
    const item_new = {
      ...item,
      key: nanoid(),
      content: '',
      anchor: false,
    };
    delete item_new.is_list; //删除+按钮表示字段
    pointsCopy.push(item_new);
    //重新计算索引
    let idx = 1;
    pointsCopy.forEach((ele: any) => {
      if (ele?.title?.indexOf(ele?.anchorName) >= 0) {
        ele.title = ele.anchorName + idx;
        idx++;
      }
    });
    setPoints(pointsCopy);
  };
  const removeItem2 = (index: number) => {
    const pointsCopy: any = [...points];
    pointsCopy.splice(index, 1);
    //重新计算索引
    let idx = 1;
    pointsCopy.forEach((ele: any) => {
      if (ele?.title?.indexOf(ele?.anchorName) >= 0) {
        ele.title = ele.anchorName + idx;
        idx++;
      }
    });
    setPoints(pointsCopy);
  };

  const handleChange = (val: any) => {
    if (/^(?!0)[1-9][0-9]?$/.test(val)) {
      setArticlesNum(val);
      let seconds = 0;
      if (val < 10) {
        setArticlesNumTip(`小麦支持同时生成多篇文章，建议您多选择几篇进行生成`);
      } else if (val > 30) {
        setArticlesNumTip(`小麦预计耗时较长，您可以先处理其他事务，稍后查看`);
      } else {
        seconds = val * 5; // 1 对应 5 秒
        const minutes = Math.ceil(seconds / 60);
        setArticlesNumTip(`小麦将全力加速生成您的文章，预计耗时 ${minutes} 分钟`);
      }
    }
  };

  useEffect(() => {
    handleChange(articles_expected);
  }, [articles_expected]);

  //取消编辑 数据重置
  const cancelEdit = () => {
    setArticlesNum(articles_expected); //重置篇数
    //重置 要点列表
    const keyPointsNew = keyPoints.map((item: any) => {
      return {
        key: nanoid(),
        ...item,
      };
    });
    setPoints(keyPointsNew);
    computeLabelWidth();
    editAglin(false);
  };
  return (
    <div className="gen-content">
      <div className="title">
        <div>{!loading ? '关键信息' : '正在提炼要点……'}</div>
        {!loading && (
          <div className="edit">
            {!edit ? (
              <div onClick={() => editAglin(true)} style={{ color: '#3E4352', cursor: 'pointer' }}>
                <FormOutlined style={{ marginRight: '6px' }} />
                编辑
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'row', color: '#979797' }}>
                <div
                  onClick={() => cancelEdit()}
                  style={{ color: '#3E4352', opacity: '0.7', cursor: 'pointer', padding: '0 10px' }}
                >
                  取消
                </div>{' '}
                |
                <div
                  onClick={general}
                  style={{ color: '#397BFF', cursor: 'pointer', paddingLeft: '10px' }}
                >
                  生成
                </div>
              </div>
            )}
          </div>
        )}
      </div>
      {points.length > 0 &&
        points.map((item: any, index: number) => {
          return (
            <div className="genral-list" key={item.key}>
              <div className={`genral-list-hd ${!edit ? 'vamiddle' : ''}`} style={labelStyle}>
                <span>{item.title}:</span>
                {item.can_add === 1 && edit && (
                  <Button
                    type="text"
                    size="small"
                    shape="circle"
                    icon={<PlusCircleOutlined />}
                    onClick={() => addItem(index)}
                  />
                )}
                {item.anchor && edit && (
                  <Button
                    type="text"
                    size="small"
                    shape="circle"
                    icon={<PlusCircleOutlined />}
                    onClick={() => addItem2(index)}
                  />
                )}
                {!item.anchor && item?.title.indexOf(item?.anchorName) >= 0 && edit && (
                  <Button
                    type="text"
                    size="small"
                    shape="circle"
                    icon={<MinusCircleOutlined />}
                    onClick={() => removeItem2(index)}
                  />
                )}
              </div>
              <div className="genral-list-bd">
                <TextArea
                  placeholder="输入该信息文章会生成的更好"
                  bordered={false}
                  disabled={disabled}
                  autoSize={{ maxRows: 50, minRows: 1 }}
                  value={item.content}
                  onChange={(e) => handleChangeParaEdit(index, e)}
                ></TextArea>
              </div>
            </div>
          );
        })}
      <div className="genSelectNumbox">
        <span className="genSelectNum-hd">生成的篇数</span>
        {edit ? (
          <div className="genSelectNum-ft">
            <Tooltip
              defaultOpen={false}
              trigger={['hover']}
              color="blue"
              title="请输入1-99的整数"
              placement="topLeft"
            >
              <InputNumber
                min={1}
                precision={0}
                max={99}
                defaultValue={articlesNum}
                onChange={handleChange}
                style={{ width: 60 }}
              />
            </Tooltip>

            {articlesNumTip}
          </div>
        ) : (
          <div className="genSelectNum-bd">{articlesNum}篇</div>
        )}
      </div>
    </div>
  );
};

// export default GeneralCon;
export default connect(({ highClassWrite }) => ({ highClassWrite }))(GeneralCon);
